<template>
  <div style="padding:15px" v-loading="pageLoading">
    <div class="text-wrap flex flex-center flex-col-between">
      <div class="desc-text text-primary">
        <i class="el-icon-s-grid" />
        <span class="text">订单排产进度</span>
      </div>

      <div class="filter-container" style="width: 500px;">
        <el-select class="search-div" v-model="query.orderType" clearable filterable @change="search"
          placeholder="订单类型">
          <el-option v-for="item in orderTypeList" :key="item.key" :label="item.value" :value="item.key">
          </el-option>
        </el-select>
        <!-- <el-select   v-model="query.materialId" clearable filterable
          placeholder="请输入产品信息">
          <el-option
            v-for="item in materialList"
            :key="item.key"
            :label="item.value"
            :value="item.key">
          </el-option>
        </el-select> -->
        <el-input class="search-div" v-model="query.orderNo" clearable placeholder="请输入订单号" @change="search"></el-input>
        <el-input class="search-div" v-model="query.materialName" clearable placeholder="请输入产品信息"
          @change="search"></el-input>
        <el-button type="success" plain @click="search">查询
        </el-button>
      </div>
    </div>

    <div class="container">
      <!-- 未开始 -->
      <div class="item">
        <div class="circle circle-0"></div>
        <span class="text">未开始</span>
      </div>
      <!-- 生产中 -->
      <div class="item">
        <div class="circle circle-1"></div>
        <span class="text">生产中</span>
      </div>
      <!-- 生产完成 -->
      <div class="item">
        <div class="circle circle-2"></div>
        <span class="text">生产完成</span>
      </div>
      <!-- 延迟生产中 -->
      <div class="item">
        <div class="circle circle-3"></div>
        <span class="text">延迟生产中</span>
      </div>
      <!-- 延迟生产完成 -->
      <div class="item">
        <div class="circle circle-4"></div>
        <span class="text">延迟生产完成</span>
      </div>
    </div>

    <div>
      <n-config-provider :theme-overrides="themeOverrides" style="overflow-x: auto">
        <n-data-table :bordered="false" :single-line="false" ref="table" :columns="columns" :data="data"
          :max-height="550" :scroll-x="2000" :scrollbar-props="scrollbarProps" />
      </n-config-provider>
      <z-pagination :pagination="pagination" :total="total" v-model:page="query.limit" v-model:limit="query.rows"
        @change="search"></z-pagination>
    </div>
    <el-dialog :title="`${curMoCode} - 排产信息`" width="70%" v-model="dialogVisible">
      <z-Table :list="curMoList" :tableProps="tableProps" :columns="columnsMachine">
      </z-Table>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, h, getCurrentInstance } from "vue";
import { useDraggable } from 'vue-draggable-plus'
import { NButton, NTag, useMessage, NConfigProvider, NEllipsis, NTooltip } from "naive-ui";
import commonMixin from '@/views/_common/mixin'
import dayjs from 'dayjs'
import _ from 'lodash'

export default {
  mixins: [commonMixin],
  data() {
    return {
      scrollbarProps: {
        trigger: 'none',
        size: 20,
        "content-class": "content-class",
        "x-scrollable": true,
      },
      pageLoading: false,
      dialogVisible: false,//弹框
      curMoCode: '',
      total: 0,
      themeOverrides: {},
      query: {},
      routeControlStateList: [],
      orderTypeList: [],
      orderPriorityList: [],
      WMS_OrderStatusList: [],
      data: [],
      tableProps: {
        border: true,
        'scrollbar-always-on':true,
        hideOperations: true,
      },
      curMoList: [],
      columnsMachine: [
        { title: '设备编码', key: 'MachineCode', width: 150 },
        { title: '设备名称', key: 'MachineName', width: 200 },
        { title: '工单号', key: 'MoCode' , width: 120 },
        { title: '投料批号', key: 'PreMoCode' , width: 120 },
        { title: '工序状态', key: 'routeControlState', width: 120  },
        { title: '计划开始', key: 'planStart', width: 180 },
        { title: '计划结束', key: 'planEnd', width: 180 },
        { title: '实际开始', key: 'productionStart', width: 180 },
        { title: '实际结束', key: 'productionEnd', width: 180 },
        { title: '计划数量', key: 'planQty' , width: 120 },
        { title: '实际产出量', key: 'producedQty', width: 120 },
      ],
      BasColumns: [
        // {
        //   type: "selection",
        //   fixed: "left"
        // },
        {
          title: "订单类型",
          key: "orderType",
          width: 100,
          fixed: "left",
          render: (row) => h(NEllipsis, { lineClamp: 1, tooltip: true }, () => row.orderType)
        },
        {
          title: "订单号",
          key: "orderNo",
          width: 100,
          fixed: "left",
          render: (row) => h(NEllipsis, { lineClamp: 1, tooltip: true }, () => row.orderNo)
        },
        {
          title: "产品信息",
          key: "materialName",
          width: 120,
          // fixed: "left"
          render: (row) => h(NEllipsis, { lineClamp: 1, tooltip: true }, () => row.materialName)
        },
        {
          title: "下单日期",
          key: "orderDate",
          width: 180,
          // fixed: "left"
          render: (row) => h(NEllipsis, { lineClamp: 1, tooltip: true }, () => row.orderDate)
        },
        {
          title: "要求交付日期",
          key: "requiredDate",
          width: 180,
          // fixed: "left"
          render: (row) => h(NEllipsis, { lineClamp: 1, tooltip: true }, () => row.requiredDate)
        },
        {
          title: "客户信息",
          key: "customerFullName",
          width: 180,
          // fixed: "left"
          render: (row) => h(NEllipsis, { lineClamp: 1, tooltip: true }, () => row.customerFullName)
        },
        {
          title: "投产状态",
          key: "orderStatus",
          width: 100,
          // fixed: "right",
          render: (row) => h(NEllipsis, { lineClamp: 1, tooltip: true }, () => row.orderStatus)
        },
        {
          title: "订单数量",
          key: "totalQty",
          width: 100,
          // fixed: "right",
          render: (row) => h(NEllipsis, { lineClamp: 1, tooltip: true }, () => row.totalQty)
        },
        {
          title: "投产日期",
          key: "productionDate",
          width: 180,
          // fixed: "right",
          render: (row) => h(NEllipsis, { lineClamp: 1, tooltip: true }, () => row.productionDate)
        },
        {
          title: "计划产出日期",
          key: "plannedOutputDate",
          width: 180,
          // fixed: "right",
          render: (row) => h(NEllipsis, { lineClamp: 1, tooltip: true }, () => row.plannedOutputDate)
        },
        {
          title: "已产出量",
          key: "producedQty",
          width: 90,
          // fixed: "right",
          render: (row) => h(NEllipsis, { lineClamp: 1, tooltip: true }, () => row.producedQty)
        },
        {
          title: "优先级",
          key: "orderPriority",
          width: 70,
          // fixed: "right",
          render: (row) => h(NEllipsis, { lineClamp: 1, tooltip: true }, () => row.orderPriority)
        },
      ],
      columns: [],
    }
  },
  mounted() {
    this.initData2()
    this.themeOverrides = {
      common: {
        primaryColor: '#7606E6'
      },
      Button: {
        textColor: '#7606E6'
      },
      Select: {
        peers: {
          InternalSelection: {
            textColor: '#7606E6'
          }
        }
      }
    }
  },
  methods: {
    titleRender(data, items) {
      return h("div", {
        style: 'color:orange;width: 60px;',
      }, data);
    },
    search() {
      this.pageLoading = true
      let data = {
        ...this.query,
      }

      this.http.post('/api/Aps_SalesOrder/GetProgressPages', data).then(r => {
        this.pageLoading = false
        this.renderData(r)
      }).catch(error => {
        this.pageLoading = false; // 关闭加载状态
      })
    },
    // 造数据
    renderData(r) {
      let that = this
      const { total, orders, configSeq } = r;
      this.total = total
      this.columns = _.cloneDeep(this.BasColumns);
      this.data = orders.map(i => {
        return {
          ...i,
          key: i.salesOrderId
        };
      });

      this.data.forEach(t => {
        // 单据类型
        let orderType = this.orderTypeList.find(d => d.key == t.orderType);
        if (orderType) {
          t.orderType = orderType.value;
        }
        // 优先级
        let orderPriority = this.orderPriorityList.find(d => d.key == t.orderPriority);
        if (orderPriority) {
          t.orderPriority = orderPriority.value;
        }

        //单据状态
        let orderStatus = this.WMS_OrderStatusList.find(d => d.key == t.orderStatus);
        if (orderStatus) {
          t.orderStatus = orderStatus.value;
        }
      });

      //模拟多条数据
      // this.data = this.data.concat(this.data, this.data, this.data, this.data)

      // 添加动态列
      configSeq.forEach(t => {
        this.columns.push({
          title: this.titleRender(t.name, null),
          key: t.code, // 使用 code 作为 key
          width: 80,
          render: (row) => { // 使用箭头函数确保 this 指向正确
            // 根据 groupId 找到对应的 routeControlState
            const stateItem = row.configState.find(item => item.groupId == t.groupId);

            // 如果没有匹配的 stateItem，则不显示圆形
            if (!stateItem) {
              return h("div"); // 返回一个空的 div
            }

            const routeControlState = stateItem.routeControlState; // 默认值为 0

            // 根据 routeControlState 设置颜色
            const colorMap = {
              '0': 'gray', // 灰色
              '1': 'blue', // 蓝色
              '2': 'green', // 绿色
              '3': 'tan', // 土黄色
              '4': 'orange' // 橙色
            };
            const color = colorMap[routeControlState] || 'gray'; // 默认灰色
            return h(

              NTooltip, // 使用 NTooltip 包裹
              {
                trigger: 'hover', // 鼠标悬停触发
                placement: 'top' // 提示信息显示在顶部
              },
              {
                default: () => {
                  let d = this.routeControlStateList.find(t => t.key == stateItem.routeControlState)
                  if (d) {
                    return d.value
                  } else {
                    return '未定义'
                  }
                }, // 提示信息内容
                trigger: () =>
                  h(
                    'div', // 父容器
                    {
                      style: {
                        display: 'flex',
                        justifyContent: 'center',
                        alignItems: 'center',
                        width: '100%',
                        height: '100%'
                      },
                      onClick: (e) => {
                        e.stopPropagation(); // 阻止事件冒泡
                        that.handleTitleClick(t.name, row); // 调用点击事件处理函数
                      }
                    },
                    [
                      h('div', {
                        // 圆形
                        style: {
                          width: '20px',
                          height: '20px',
                          borderRadius: '50%',
                          backgroundColor: color
                        }
                      })
                    ]
                  ),
              },
            );
          }
        });
      });

      this.columns.push({
        title: "更新时间",
        key: "modifyTime",
        width: 160,
        fixed: "right",
        render: (row) => h(NEllipsis, { lineClamp: 1, tooltip: true }, () => row.modifyTime)
      });
    },
    initData2() {
      this.pageLoading = true

      //查询字典值
      this.http
        .post('api/Sys_Dictionary/GetVueDictionary', [
          "APS_OrderType",
          "APS_RouteControlState",
          "APS_OrderPriority",
          "WMS_OrderStatus"
        ])
        .then((r) => {
          console.log(r)
          r.forEach(t => {
            //订单工序状态
            if (t.DictionaryNo == 'APS_RouteControlState') {
              this.routeControlStateList = t.data
            }
            //订单优先级
            if (t.DictionaryNo == 'APS_OrderPriority') {
              this.orderPriorityList = t.data
            }
            //订单类型
            if (t.DictionaryNo == 'APS_OrderType') {
              this.orderTypeList = t.data
            }
            //单据状态
            if (t.DictionaryNo == 'WMS_OrderStatus') {
              this.WMS_OrderStatusList = t.data
            }
          })
        })

      this.query = {
        'orderType': null,
        'materialName': null,
        'orderNo': null,
        'limit': 1,
        'rows': 10
      }
      this.search()
    },
    handleTitleClick(name, row) {
      this.curMoCode = row.orderNo+" - "+name
      this.http.get('api/Aps_SalesOrder/GetDetailPage', { groupName: name, orderId: row.salesOrderId }).then(r => {
        this.curMoList = [...r]
        if (this.curMoList.length == 0) {
          this.$message.info('当前步骤未排产')
          return
        }
        this.curMoList.forEach(item => {
          let d = this.routeControlStateList.find(t => t.key == item.routeControlState)
          if (d) {
            item.routeControlState = d.value
          } else {
            item.routeControlState = '未定义'
          }
        })
      }).finally(() => {
        if (this.curMoList.length > 0) {
          this.dialogVisible = true
        }
      })
    },
  },
  ageRender(row, index) {
    return h("div", {
      style: 'color:red;cursor: pointer;',
      //onClick: (e) => this.handleAgeClick(row, index, e)
    }, dayjs(row.DeadLine).format('MM-DD'));
  },

}
</script>

<style lang="scss" scoped>
.text-wrap {
  height: 40px;
  position: relative;
  padding-bottom: 8px;
  display: flex;

  .desc-text {
    //  display: inline-block;
    margin-top: 7px;
    font-weight: bold;
    //margin-bottom: 3px;
    font-size: 14px;
    white-space: nowrap;
    border-bottom: 2px solid #7300e6;

    i {
      font-size: 16px;
      position: relative;
      top: 1px;
      margin-right: 2px;
    }
  }
}
::v-deep .n-scrollbar-rail--vertical--right>.n-scrollbar-rail__scrollbar {
  background-color: #b9b9b9a7 !important;
}

::v-deep .n-scrollbar-rail--horizontal--bottom>.n-scrollbar-rail__scrollbar {
  background-color: #b9b9b9a7 !important;
  height: 30px !important;
}
.search-div {
  padding-right: 5px;
}

.container {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  gap: 16px;
}

.item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.circle {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  cursor: pointer;
}

.circle-0 {
  background-color: gray;
  /* 灰色 */
}

.circle-1 {
  background-color: blue;
  /* 蓝色 */
}

.circle-2 {
  background-color: green;
  /* 绿色 */
}

.circle-3 {
  background-color: tan;
  /* 土黄色 */
}

.circle-4 {
  background-color: orange;
  /* 橙色 */
}

.text {
  font-size: 14px;
  color: black;
}
</style>
